package com.campus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.campus.dao.SysUserMapper;
import com.campus.entry.SysUser;
import com.campus.exception.BusinessException;
import com.campus.pojo.dto.SysUserDto;
import com.campus.response.ResultCode;
import com.campus.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 新增一名用户
     * @param sysUser
     */
    @Override
    public void saveSysUser(SysUser sysUser) {
        sysUserMapper.insert(sysUser);
    }

    /**
     * 根据Id查询用户
     * @param sysUserId
     * @return {@link SysUser }
     */
    @Override
    public SysUser getSysUserById(Integer sysUserId) {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(SysUser::getId,sysUserId);
        return sysUserMapper.selectOne(lambdaQueryWrapper);
    }

    /**
     * 根据用户名查询用户
     * @param loginName
     * @return {@link SysUser }
     */
    @Override
    public SysUser getSysUserByName(String loginName) {
         LambdaQueryWrapper<SysUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();
         lambdaQueryWrapper
                 .eq(SysUser::getLoginName,loginName);
         return sysUserMapper.selectOne(lambdaQueryWrapper);
    }

    /**
     * 更新用户
     * @param sysUser
     */
    @Override
    public void updateSysUser(SysUser sysUser) {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(SysUser::getId,sysUser.getId());
        sysUserMapper.update(sysUser,lambdaQueryWrapper);
    }

    /**
     * 保存用户身份
     * @param userId
     * @param role
     */
    @Override
    public void saveRole(Integer userId, String role){
        sysUserMapper.insertRole(userId,role);
    }

    /**
     * 根据用户名获取用户Id
     * @param loginName
     * @return {@link Integer }
     */
    @Override
    public Integer getUserIdByUserName(String loginName) {
        Integer userIdByLoginName = sysUserMapper.getUserIdByLoginName(loginName);
        if (Objects.isNull(userIdByLoginName)){
            throw new BusinessException(ResultCode.NO_REGISTER);
        }

        return  userIdByLoginName;
    }

    @Override
    public String gertRoleById(Integer id) {
        return sysUserMapper.getRoleById(id);
    }

    @Override
    public List<SysUserDto> listSysUser() {
        return sysUserMapper.listSysUer();
    }

    @Override
    public void removeSysUserById(Integer id) {

    }

    @Override
    public void updateState(String state,Integer id) {

        sysUserMapper.updateStatus(state,id);
    }

}
